package yiran.stock.manager;

import yiran.stock.output.Logger;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

public class StockCacheManager {
    public final Map<String, Double> stockPrices = new ConcurrentHashMap<>();
    public final Map<String, Double> previousPrices = new ConcurrentHashMap<>();
    public final Map<String, String> stockNames = new ConcurrentHashMap<>();
    public final Map<String, Long> lastApiCall = new ConcurrentHashMap<>();
    public final Set<String> loadedStocks = new ConcurrentSkipListSet<>();

    public boolean isStockLoaded(String symbol) {
        return loadedStocks.contains(symbol.toLowerCase());
    }

    public void markStockLoaded(String symbol) {
        loadedStocks.add(symbol.toLowerCase());
    }

    public String getStockName(String symbol) {
        String name = stockNames.get(symbol.toLowerCase());
        return (name != null && !name.equalsIgnoreCase(symbol)) ? name : null;
    }

    public void cacheStockName(String symbol, String name) {
        if (name == null) {
            Logger.error("尝试缓存空名称的股票: " + symbol);
            name = "未知股票";
        }
        stockNames.put(symbol.toLowerCase(), name);
    }

    public void cacheStockPrice(String symbol, double price) {
        stockPrices.put(symbol.toLowerCase(), price);
    }

    public void cachePreviousPrice(String symbol, double price) {
        previousPrices.put(symbol.toLowerCase(), price);
    }

    public Double getCachedPrice(String symbol) {
        return stockPrices.get(symbol.toLowerCase());
    }

    public Double getPreviousPrice(String symbol) {
        return previousPrices.get(symbol.toLowerCase());
    }

    public boolean isCacheValid(String symbol, long cacheTime) {
        String lowerSymbol = symbol.toLowerCase();
        return lastApiCall.containsKey(lowerSymbol) &&
                (System.currentTimeMillis() - lastApiCall.get(lowerSymbol)) < cacheTime;
    }

    public void updateLastApiCall(String symbol) {
        lastApiCall.put(symbol.toLowerCase(), System.currentTimeMillis());
    }

    public Map<String, Double> getAllStockPrices() {
        return new ConcurrentHashMap<>(stockPrices);
    }
}
